package cn.jnetty.ioc.definition;

import cn.jnetty.api.annotation.JResource;
import cn.jnetty.api.exception.JnettyIocException;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

/**
 * @author 猪哥亮
 * @email 1030681978@qq.com
 * @date 2020/4/3 18:22
 * 描述：
 */
public class JResourceBeanDefinition extends JDefaultBeanDefinition {
    private Field field;
    private Object bean;

    public JResourceBeanDefinition(JResource resource, Field field, Object bean) {
        super(resource,field.getType());
        this.bean = bean;
        this.field = field;
        init();
    }

    @Override
    protected void init() {
        try {
            field.setAccessible(true);
            Field modifiersField = Field.class.getDeclaredField("modifiers");
            modifiersField.setAccessible(true);
            modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
            //这里的值要从ioc中去取
            Object var = JDefaultBeanDefinitionFactory.getInstance().getBean(((JResource)annotation).path());
            if (var != null) {
                field.set(this.bean, var);
            } else {
                if (((JResource)annotation).required()) {
                    throw new JnettyIocException("注入的bean不能为空，如果该值可以为空请使用required = false在<<{0}>>的=={1}",bean.getClass().getName(),field.getType().getName());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
